<?php

namespace app\Api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use think\Config;
use addons\weixin\library\WechatService;
use app\admin\model\weixin\User as WechatUser;
use app\admin\model\weixin\template\Wechat as WechatTemplate;
use think\Hook;
use think\Cookie;

/**
 * 微信公众号接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['messageSend'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 微信消息推送
     */
    public function messageSend(){
        $first = $this->request->post('first', '') ?: '您请注意！';
        $remark = $this->request->post('remark', '');
        $keyword1 = $this->request->post('type', '');
        $keyword2 = $this->request->post('device', '');
        $keyword3 = $this->request->post('time', '') ?: date('Y-m-d H:i:s');
        $keyword4 = $this->request->post('content', '');
        $uid = $this->request->post('uid', '2');
        if(empty($keyword1) || empty($keyword2) || empty($keyword4)){
            $this->error('参数异常: type or device or content');
        }
/*
{{first.DATA}}
报警类型：{{keyword1.DATA}}
报警设备：{{keyword2.DATA}}
报警时间：{{keyword3.DATA}}
报警内容：{{keyword4.DATA}}
{{remark.DATA}}
*/
        $data = [
            'first'=>$first,
            'keyword1'=>$keyword1,
            'keyword2'=>$keyword2,
            'keyword3'=>$keyword3,
            'keyword4'=>$keyword4,
            'remark'=>$remark,
        ];

        try{
            $openId = WechatUser::uidToOpenid($uid, 'openid');
            $tempid = WechatTemplate::tempkeyToTempid('DEVICE_ALARM') ?: '3ovggzn7N_uMPM1Ao7PHKmJePImj_c1Zwezgi82ngPs';
            $result = WechatService::sendTemplate($openId, $tempid, $data);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        if(isset($result['errcode']) && $result['errcode'] === 0){
            $this->success('发送成功');
        }
        $this->error('发送失败');
    }

}
